<template>
  <div class="page-container">
    <div class="form-container">
      <h2>用户注册</h2>
      <TInput
        v-model="username"
        label="用户名"
        required
        placeholder="请输入用户名"
        :validator="usernameValidator"
      />
      <TInput
        v-model="email"
        label="邮箱"
        required
        placeholder="请输入邮箱"
        :validator="emailValidator"
      />
      <TInput
        v-model="password"
        label="密码"
        required
        placeholder="请输入密码"
        :validator="passwordValidator"
      />
      <Tbutton type="primary" block @click="handleSubmit">注册</Tbutton>
      <Tbutton type="ghost" block @click="handleLogin">登录</Tbutton>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import TInput from "@/components/TInput.vue";
import Tbutton from "@/components/TButton.vue";
import { validators } from "@/utils/validators"; // 导入基础验证器

const username = ref("");
const email = ref("");
const password = ref("");

// 邮箱验证器
const emailValidator = (value: string) => {
  return validators.emailValidator(value);
};

// 密码验证器
const passwordValidator = async (value: string) => {
  const lengthValid = validators.lengthValidator(value);
  if (!lengthValid.valid) {
    return lengthValid;
  }
  // 2. 异步验证
  const asyncCheck = await validators.asyncValidator(value);
  return asyncCheck;
};
// 组合验证器：先长度验证，再异步验证
const usernameValidator = async (value: string) => {
  // 1. 长度验证
  const lengthCheck = validators.lengthValidator(value);
  if (!lengthCheck.valid) {
    return lengthCheck;
  }

  // 2. 异步验证
  const asyncCheck = await validators.asyncValidator(value);
  return asyncCheck;
};
const handleSubmit = () => {
  console.log("提交");
};

const handleLogin = () => {
  console.log("登录");
};
</script>
<style scoped>
.form-container {
  width: 600px;
  margin: 20px auto;
}
</style>
